package com.mmall.controller.common.interceptors;

import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.util.CookieUtil;
import com.mmall.util.JsonUtil;
import com.mmall.util.RedisShardedPoolUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) o;
        String methdoName =  handlerMethod.getBeanType().getName();
        String beanName = handlerMethod.getBean().getClass().getSimpleName();

        // 解析参数,打印日志
        Map paramMap = httpServletRequest.getParameterMap();
        Iterator it = paramMap.entrySet().iterator();
        StringBuffer requestParamBuffer = new StringBuffer();
        while(it.hasNext()){
           Map.Entry entry = (Map.Entry) it.next();
           String key = entry.getKey().toString();
           String value = StringUtils.EMPTY;
           if(entry.getValue() instanceof String[]){
                String[] arr = (String[]) entry.getValue();
                value = Arrays.toString(arr);
           }
           requestParamBuffer.append(key+"="+value);
        }

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        User user = null;
        if(StringUtils.isNotEmpty(loginToken)){
            String userStr = RedisShardedPoolUtil.get(loginToken);
            user = JsonUtil.string2Obj(userStr,User.class);
        }

        if(user == null || user.getRole().intValue() != Const.Role.ROLE_ADMIN){
            httpServletResponse.reset(); // 要加这个reset(),否则getwriter（）会抛出异常
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json;chartset=UTF-8");
            PrintWriter out = httpServletResponse.getWriter();
            if(user==null){
                out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户未登录")));
            }
            else {
                out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户无权限")));
            }
            out.flush();
            out.close();
            return false;// 不会再继续下去了，contoller不会被调用
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
